package com.lanou.beautifulwardrobe.dbHelper;

import android.util.Log;

import com.lanou.beautifulwardrobe.application.BaseApplication;
import com.lanou.beautifulwardrobe.entity.greendao.DaoSession;
import com.lanou.beautifulwardrobe.entity.greendao.UsersEntity;
import com.lanou.beautifulwardrobe.entity.greendao.UsersEntityDao;

import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 15/11/9.
 */
public class UsersDBHelper {
    private static UsersDBHelper helper;
    private static DaoSession daoSession;

    private UsersDBHelper() {

    }

    public static UsersDBHelper getInstance() {
        if (helper == null) {
            helper = new UsersDBHelper();
            daoSession = BaseApplication.getDaoSession();
        }
        return helper;
    }

    /**
     * 插入一个用户对象
     *
     * @param usersEntity
     */
    public void addUser(UsersEntity usersEntity) {
        daoSession.getUsersEntityDao().insertInTx(usersEntity);
        Log.i("lanou","增加一用户***");
    }

    /**
     * 查询某个表是否包含某个用户:
     *
     * @param user
     * @return
     */
    public boolean isSaved(String user) {
        QueryBuilder<UsersEntity> db = daoSession.getUsersEntityDao().queryBuilder();
        db.where(UsersEntityDao.Properties.User.eq(user));
        db.buildCount().count();
        return db.buildCount().count() > 0 ? true : false;
    }

    /**
     * 按用户名查询
     * @param user
     * @return
     */
    public UsersEntity queryByUser(String user){
        QueryBuilder<UsersEntity> db = daoSession.getUsersEntityDao().queryBuilder();
        db.where(UsersEntityDao.Properties.User.eq(user));
        return db.list().get(0);
    }
    /**
     * 查询所有
     * @return
     */
    public List<UsersEntity> queryAll(){
        return  daoSession.getUsersEntityDao().loadAll();
    }

    /**
     * 修改用户密码
     * @param usersEntity
     */
    public void upDate(UsersEntity usersEntity){
        daoSession.insertOrReplace(usersEntity);
    }
}
